package com.bluewave.goaltracker.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ApplicationDBAdapter {

	private static final String DATABASE_NAME = "GoalKeeperDataBase.db";
	private static final String GOAL_TABLE = "goalTable";
	private static final String GOAL_UPDATE_TABLE = "goalUpdateTable";

	private static final int DATABASE_VERSION = 2;

	// The index (key) column name for use in where clauses.
	public static final String GOAL_KEY_ID = "_id";
	public static final String GOAL_UPDATE_KEY_ID = "_id";

	// The name and column index of each column in your database.
	public static final String GOAL_NAME = "goalName";
	public static final String GOAL_TYPE = "goalType";
	public static final String GOAL_CREATED_DATE = "createdDate";
	public static final String GOAL_TRACK_PERIOD = "trackPeriod";
	public static final String GOAL_TRACK_DAY = "trackDay";

	public static final int NAME_COLUMN = 1;
	// TODO: Create public field for each column in your table.

	public static final String GOAL_UPDATE_DATE = "updateDate";
	public static final String GOAL_UPDATE_STATUS = "status";
	public static final String GOAL_ID = "goalId";

	// SQL Statement to create a new database.
	private static final String DATABASE_CREATE_GOAL = "create table "
			+ GOAL_TABLE + " (" + GOAL_KEY_ID
			+ " integer primary key autoincrement, " + GOAL_NAME
			+ " integer not null ," + GOAL_TYPE 
			+ " text ," + GOAL_CREATED_DATE
			+ " text not null ," + GOAL_TRACK_PERIOD 
			+ " integer not null, " + GOAL_TRACK_DAY 
			+ " integer not null);";

	// SQL Statement to create a new database.
	private static final String DATABASE_CREATE_GOAL_UPDATE = "create table "
			+ GOAL_UPDATE_TABLE + " (" + GOAL_UPDATE_KEY_ID
			+ " integer primary key autoincrement, " + GOAL_UPDATE_DATE
			+ " text not null ," + GOAL_ID + " integer not null, "
			+ GOAL_UPDATE_STATUS + " integer not null )" + ";";

	// Variable to hold the database instance
	private SQLiteDatabase db;
	// Context of the application using the database.
	private final Context context;
	// Database open/upgrade helper
	private myDbHelper dbHelper;

	private int nProgress;
	private int nDays_counter;

	public ApplicationDBAdapter(Context _context) {
		context = _context;
		dbHelper = new myDbHelper(context, DATABASE_NAME, null,
				DATABASE_VERSION);

	}

	public ApplicationDBAdapter open() throws SQLException {
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
	}

	public int insertGoal(Goal goal) {
		ContentValues newValues = new ContentValues();
		newValues.put(GOAL_NAME, goal.getGoalName());
		newValues.put(GOAL_TYPE, goal.getGoalType());
		newValues.put(GOAL_CREATED_DATE, goal.getCreatedDate());
		newValues.put(GOAL_TRACK_PERIOD, goal.getTrackPeriod());
		newValues.put(GOAL_TRACK_DAY, goal.getTrackDay());

		long index = db.insert(GOAL_TABLE, null, newValues);
		return (int) index;
	}

	public int updateGoal(Goal goal) {

		ContentValues newValues = new ContentValues();

		newValues.put(GOAL_NAME, goal.getGoalName());
		newValues.put(GOAL_TYPE, goal.getGoalType());
		//newValues.put(GOAL_CREATED_DATE, goal.getCreatedDate());
		newValues.put(GOAL_TRACK_PERIOD, goal.getTrackPeriod());
		newValues.put(GOAL_TRACK_DAY, goal.getTrackDay());

		long index = db.update(GOAL_TABLE, newValues,
				GOAL_KEY_ID + "=" + goal.getId(), null);

		return (int) index;
	}

	public boolean removeGoal(long _rowIndex) {
		return db.delete(GOAL_TABLE, GOAL_KEY_ID + "=" + _rowIndex, null) > 0;
	}

	public Cursor getAllGoalsCursor() {
		return db.query(GOAL_TABLE, null, null, null, null, null, null);
	}

	public Cursor getGoalsCursor(int type) {
		return db.query(GOAL_TABLE, null, GOAL_TYPE + " = " + type, null, null,
				null, null);
	}

	public List<Goal> getAllGoalsList() {

		List<Goal> goalList = new ArrayList<Goal>();

		Cursor cursor = db
				.query(GOAL_TABLE, null, null, null, null, null, null);

		// Make sure there is at least one row.
		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {
				int id = cursor.getInt(cursor.getColumnIndex(GOAL_KEY_ID));
				String name = cursor
						.getString(cursor.getColumnIndex(GOAL_NAME));
				int type = cursor.getInt(cursor.getColumnIndex(GOAL_TYPE));

				String createdDate = cursor.getString(cursor
						.getColumnIndex(GOAL_CREATED_DATE));
				int trackPeriod = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_PERIOD));
				int trackDay = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_DAY));

				goalList.add(new Goal(id, name, type, createdDate, trackPeriod, trackDay));
			} while (cursor.moveToNext());
		}

		cursor.close();

		return goalList;
	}

	public List<Goal> getGoalsList(int goalType) {

		List<Goal> goalList = new ArrayList<Goal>();

		Cursor cursor = db.query(GOAL_TABLE, null,
				GOAL_TYPE + " = " + goalType, null, null, null, null);

		// Make sure there is at least one row.
		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {
				int id = cursor.getInt(cursor.getColumnIndex(GOAL_KEY_ID));
				String name = cursor
						.getString(cursor.getColumnIndex(GOAL_NAME));
				int type = cursor.getInt(cursor.getColumnIndex(GOAL_TYPE));

				String createdDate = cursor.getString(cursor
						.getColumnIndex(GOAL_CREATED_DATE));
				int trackPeriod = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_PERIOD));
				int trackDay = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_DAY));
				
				goalList.add(new Goal(id, name, type, createdDate, trackPeriod, trackDay));
			} while (cursor.moveToNext());
		}

		cursor.close();

		return goalList;
	}

	public Goal getGoal(long _rowIndex) {
		Cursor cursor = db.query(GOAL_TABLE, null, GOAL_KEY_ID + " = "
				+ _rowIndex, null, null, null, null);

		Goal goal = null;

		// Make sure there is at least one row.
		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {
				int id = cursor.getInt(cursor.getColumnIndex(GOAL_KEY_ID));
				String name = cursor
						.getString(cursor.getColumnIndex(GOAL_NAME));
				int type = cursor.getInt(cursor.getColumnIndex(GOAL_TYPE));

				String createdDate = cursor.getString(cursor
						.getColumnIndex(GOAL_CREATED_DATE));
				int trackPeriod = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_PERIOD));
				int trackDay = cursor.getInt(cursor.getColumnIndex(GOAL_TRACK_DAY));
				
				goal = new Goal(id, name, type, createdDate, trackPeriod, trackDay);
			} while (cursor.moveToNext());
		}

		cursor.close();

		return goal;

	}

	public int insertGoalUpdate(GoalUpdate goalUpdate) {
		// TODO: Create a new ContentValues to represent my row
		// and insert it into the database.

		ContentValues newValues = new ContentValues();
		newValues.put(GOAL_UPDATE_DATE, goalUpdate.getGoalUpdateDate());
		newValues.put(GOAL_ID, goalUpdate.getGoalId());
		newValues.put(GOAL_UPDATE_STATUS, goalUpdate.isGoalStatus());

		long index = db.insert(GOAL_UPDATE_TABLE, null, newValues);
		return (int) index;
	}

	public int updateGoalUpdate(GoalUpdate goalUpdate) {
		// TODO: Create a new ContentValues to represent my row
		// and insert it into the database.

		ContentValues newValues = new ContentValues();
		newValues.put(GOAL_UPDATE_DATE, goalUpdate.getGoalUpdateDate());
		newValues.put(GOAL_ID, goalUpdate.getGoalId());
		newValues.put(GOAL_UPDATE_STATUS, goalUpdate.isGoalStatus());
		long index = db.update(GOAL_UPDATE_TABLE, newValues, GOAL_UPDATE_KEY_ID
				+ "=" + goalUpdate.getId(), null);

		return (int) index;
	}

	public boolean removeGoalUpdate(long _rowIndex) {
		return db.delete(GOAL_UPDATE_TABLE, GOAL_UPDATE_KEY_ID + "="
				+ _rowIndex, null) > 0;
	}

	public Cursor getAllGoalUpdatesCursor() {
		return db.query(GOAL_UPDATE_TABLE, null, null, null, null, null, null);
	}

	public List<GoalUpdate> getAllGoalUpdatesList() {

		List<GoalUpdate> goalUpdateList = new ArrayList<GoalUpdate>();

		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null, null, null, null,
				null, null);

		// Make sure there is at least one row.
		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {
				int id = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_KEY_ID));
				String updateDate = cursor.getString(cursor
						.getColumnIndex(GOAL_UPDATE_DATE));
				int status = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_STATUS));
				long goalId = cursor.getLong(cursor.getColumnIndex(GOAL_ID));

				GoalUpdate goalUpdate = new GoalUpdate(id, goalId, updateDate,
						status);

				goalUpdateList.add(goalUpdate);
			} while (cursor.moveToNext());
		}

		cursor.close();

		return goalUpdateList;
	}

	public GoalUpdate getGoalUpdate(long _rowIndex) {

		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null, GOAL_UPDATE_KEY_ID
				+ " = " + _rowIndex, null, null, null, null);

		GoalUpdate goalUpdate = null;

		// Make sure there is at least one row.
		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {
				int id = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_KEY_ID));
				String updateDate = cursor.getString(cursor
						.getColumnIndex(GOAL_UPDATE_DATE));
				int status = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_STATUS));
				long goalId = cursor.getLong(cursor.getColumnIndex(GOAL_ID));

				goalUpdate = new GoalUpdate(id, goalId, updateDate, status);
			} while (cursor.moveToNext());
		}

		cursor.close();

		return goalUpdate;
	}

	public boolean getGoalUpdateStatus(long goal_Id, String date) {
		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null,
				GOAL_ID + " = " + goal_Id + " AND " + GOAL_UPDATE_DATE
						+ " LIKE '" + date + "'", null, null, null, null);

		int status = 0;
		boolean bStatus;

		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {

				status = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_STATUS));

				bStatus = status == 1 ? true : false;

			} while (cursor.moveToNext());
		} else {

			bStatus = false;

		}

		cursor.close();

		return bStatus;

	}

	public boolean toggleGoalUpdateStatus(long goal_Id, String date) {
		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null,
				GOAL_ID + " = " + goal_Id + " AND " + GOAL_UPDATE_DATE
						+ " LIKE '" + date + "'", null, null, null, null);

		boolean isPresent = false;
		long goalUpdateId = 0;
		int status = 1;
		boolean bStatus;

		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {

				isPresent = true;
				goalUpdateId = cursor.getLong(cursor
						.getColumnIndex(GOAL_UPDATE_KEY_ID));
				status = cursor.getInt(cursor
						.getColumnIndex(GOAL_UPDATE_STATUS));

			} while (cursor.moveToNext());
		}

		if (isPresent) {

			status = status == 0 ? 1 : 0;

			updateGoalUpdate(new GoalUpdate(goalUpdateId, goal_Id, date,
					(status)));

			bStatus = status == 1 ? true : false;

		} else {

			insertGoalUpdate(new GoalUpdate(goal_Id, date, status));
			bStatus = true;

		}

		cursor.close();

		return bStatus;

	}

	public ArrayList<Date> getMarkedDateList2(long goalId, Date date, int trackPeriod) {

		Cursor goalCursor = db.query(GOAL_TABLE, null, GOAL_KEY_ID + " = "
				+ goalId, null, null, null, null);

		String goalCreationDate = null;

		if (goalCursor.moveToFirst()) {
			do {

				goalCreationDate = goalCursor.getString(goalCursor
						.getColumnIndex(GOAL_CREATED_DATE));

			} while (goalCursor.moveToNext());
		}

		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null, GOAL_ID + " = "
				+ goalId, null, null, null, null);

		ArrayList<Date> dateList = new ArrayList<Date>();

		nProgress = 0;

		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {

				String strUpdateDate = cursor.getString(cursor
						.getColumnIndex(GOAL_UPDATE_DATE));
				Date creationDate = null;

				DateFormat formatter;
				Date updateDate = null;
				formatter = new SimpleDateFormat("dd-MM-yyyy");
				try {
					updateDate = (Date) formatter.parse(strUpdateDate);
					creationDate = (Date) formatter.parse(goalCreationDate);
				} catch (ParseException e) {
					e.printStackTrace();
				}

				Date firstDate = getFirstDateOfMonth(date);
				Date lastDate = getLastDateOfMonth(date);
				Date todayDate = new Date(new Date().getYear(),
							new Date().getMonth(), new Date().getDate());
				if(trackPeriod==Goal.TrackPeriod.MONTHLY){
					todayDate=lastDate;
				}
				else if(trackPeriod==Goal.TrackPeriod.WEEKLY){
					Calendar cal=Calendar.getInstance();
					cal.add(Calendar.DATE, 6-(cal.get(Calendar.DAY_OF_WEEK))-1);
					todayDate=cal.getTime();
					todayDate.setYear(1900+todayDate.getYear());
				}

				if ((updateDate.after(creationDate) || updateDate
						.equals(creationDate))
						&& (updateDate.before(todayDate) || (updateDate
								.equals(todayDate)))) {
					if ((updateDate.after(firstDate) || updateDate
							.equals(firstDate))
							&& (updateDate.before(lastDate) || (updateDate
									.equals(lastDate)))) {

						nDays_counter++;
						// Log.i("ADBA", "inside date range ");

						int status = cursor.getInt(cursor
								.getColumnIndex(GOAL_UPDATE_STATUS));

						if (status == 1) {

							nProgress++;

							dateList.add(updateDate);

							Log.i("GOAL", nProgress + " - PP");
							Log.i("GOAL", nDays_counter + " - DC");

						}

					}

				}

			} while (cursor.moveToNext());
		}

		cursor.close();

		goalCursor.close();

		return dateList;
	}

	public float getProgressPercent(long goalId, Date date) {

		Cursor goalCursor = db.query(GOAL_TABLE, null, GOAL_KEY_ID + " = "
				+ goalId, null, null, null, null);

		String goalCreationDate = null;
		int trackPeriod=0, trackDay=0;

		if (goalCursor.moveToFirst()) {
			do {

				goalCreationDate = goalCursor.getString(goalCursor
						.getColumnIndex(GOAL_CREATED_DATE));
				trackPeriod = goalCursor.getInt(goalCursor
						.getColumnIndex(GOAL_TRACK_PERIOD));
				trackDay = goalCursor.getInt(goalCursor
						.getColumnIndex(GOAL_TRACK_DAY));

			} while (goalCursor.moveToNext());
		}

		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null, GOAL_ID + " = "
				+ goalId, null, null, null, null);

		float nDays_counter = 0;
		Date creationDate = null;
		DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
		try {
			creationDate = (Date) formatter.parse(goalCreationDate);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Date startDate = null;
		Date endDate = null;

		Date firstDate = getFirstDateOfMonth(date);
		Date lastDate = getLastDateOfMonth(date);
		Date todayDate = date;
		if(trackPeriod==Goal.TrackPeriod.MONTHLY){
			todayDate=lastDate;
		}
		else if(trackPeriod==Goal.TrackPeriod.WEEKLY){
			Calendar cal=Calendar.getInstance();
			cal.add(Calendar.DATE, 6-(cal.get(Calendar.DAY_OF_WEEK))-1);
			todayDate=cal.getTime();
			todayDate.setYear(1900+todayDate.getYear());
		}		

		if (creationDate.after(firstDate)
				|| (creationDate.equals(firstDate))) {
			startDate = creationDate;
		} else {
			startDate = firstDate;
		}

		if (todayDate.before(lastDate)
				|| (creationDate.equals(firstDate))) {
			endDate = todayDate;
		} else {
			endDate = lastDate;
		}
		
		Date s_date=startDate;
		if(trackPeriod==Goal.TrackPeriod.DAILY)
			nDays_counter = ((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;
		else if(trackPeriod==Goal.TrackPeriod.WEEKLY){
			long dayMilliSeconds=1000 * 60 * 60 * 24;
			while(s_date.before(endDate)||s_date.equals(endDate)){
				int day=s_date.getDay();
				if(day==trackDay) nDays_counter++;
				s_date=new Date(s_date.getTime()+dayMilliSeconds);
			}
		}
		else if(trackPeriod==Goal.TrackPeriod.WEEKDAYS){
			nDays_counter=getWeekdays(startDate,endDate);
		}
		else if(trackPeriod==Goal.TrackPeriod.WEEKENDS){
			long dayMilliSeconds=1000 * 60 * 60 * 24;
			while(s_date.before(endDate)||s_date.equals(endDate)){
				int day=s_date.getDay();
				if(day==0||day==6) nDays_counter++;
				s_date=new Date(s_date.getTime()+dayMilliSeconds);
			}
		}
		else if(trackPeriod==Goal.TrackPeriod.MONTHLY){
			nDays_counter=1;
		}
		
		ArrayList<Date> dateList = new ArrayList<Date>();

		float nProgress = 0;

		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {

				String strUpdateDate = cursor.getString(cursor
						.getColumnIndex(GOAL_UPDATE_DATE));
				
				Date updateDate = null;
				//formatter = new SimpleDateFormat("dd-MM-yyyy");
				try {
					updateDate = (Date) formatter.parse(strUpdateDate);
					//creationDate = (Date) formatter.parse(goalCreationDate);
				} catch (ParseException e) {
					e.printStackTrace();
				}


				if ((updateDate.after(startDate) || (updateDate
						.equals(startDate)))
						&& (updateDate.before(endDate) || (updateDate
								.equals(endDate)))) {
					int status = cursor.getInt(cursor
							.getColumnIndex(GOAL_UPDATE_STATUS));

					if (status == 1) {

						nProgress++;

						dateList.add(updateDate);

					}

				}

			} while (cursor.moveToNext());
		}

		cursor.close();

		goalCursor.close();

		float nProgressPercent = 0;

		if (nDays_counter != 0) {
			Log.i("GOAL", nDays_counter + " - DC");

			nProgressPercent = (nProgress * 100) / nDays_counter;
		}
		return Round(nProgressPercent, 1);

	}

	static long getWeekdays(Date start, Date end){
	    Calendar c1 = Calendar.getInstance();
	    c1.setTime(start);
	    int w1 = c1.get(Calendar.DAY_OF_WEEK);
	    c1.add(Calendar.DAY_OF_WEEK, -w1);

	    Calendar c2 = Calendar.getInstance();
	    c2.setTime(end);
	    int w2 = c2.get(Calendar.DAY_OF_WEEK);
	    c2.add(Calendar.DAY_OF_WEEK, -w2);

	    //end Saturday to start Saturday 
	    long days = (c2.getTimeInMillis()-c1.getTimeInMillis())/(1000*60*60*24);
	    long daysWithoutSunday = days-(days*2/7);

	    return (daysWithoutSunday-w1+w2)+1;
	}
	
	public float getPreviousMonthsProgressPercent(long goalId, Date date) {

		Cursor goalCursor = db.query(GOAL_TABLE, null, GOAL_KEY_ID + " = "
				+ goalId, null, null, null, null);

		String goalCreationDate = null;

		if (goalCursor.moveToFirst()) {
			do {

				goalCreationDate = goalCursor.getString(goalCursor
						.getColumnIndex(GOAL_CREATED_DATE));

			} while (goalCursor.moveToNext());
		}

		Cursor cursor = db.query(GOAL_UPDATE_TABLE, null, GOAL_ID + " = "
				+ goalId, null, null, null, null);

		ArrayList<Date> dateList = new ArrayList<Date>();

		int nProgress = 0;
		long nDays_counter = 0;

		if (cursor.moveToFirst()) {
			// Iterate over each cursor.
			do {

				String strUpdateDate = cursor.getString(cursor
						.getColumnIndex(GOAL_UPDATE_DATE));
				Date creationDate = null;

				DateFormat formatter;
				Date updateDate = null;
				formatter = new SimpleDateFormat("dd-MM-yyyy");
				try {
					updateDate = (Date) formatter.parse(strUpdateDate);
					creationDate = (Date) formatter.parse(goalCreationDate);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Date startDate = null;
				Date endDate = null;

				Date firstDate = getFirstDateOfMonth(date);
				Date lastDate = getLastDateOfMonth(date);

				if (creationDate.after(firstDate)
						|| (creationDate.equals(firstDate))) {
					startDate = creationDate;
				} else {
					startDate = firstDate;
				}

				endDate = lastDate;

				nDays_counter = ((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;

				if ((updateDate.after(startDate) || (updateDate
						.equals(startDate)))
						&& (updateDate.before(endDate) || (updateDate
								.equals(endDate)))) {
					int status = cursor.getInt(cursor
							.getColumnIndex(GOAL_UPDATE_STATUS));

					if (status == 1) {

						nProgress++;

						dateList.add(updateDate);

					}

				}

			} while (cursor.moveToNext());
		}

		cursor.close();

		goalCursor.close();

		float nProgressPercent = 0;

		if (nDays_counter != 0) {
			Log.i("GOAL", nDays_counter + " - DC");

			nProgressPercent = (nProgress * 100) / nDays_counter;
		}
		return Round(nProgressPercent, 1);

	}

	/*public float getTotalProgress(Date date) {

		ArrayList<Goal> goals_list = (ArrayList<Goal>) getAllGoalsList();

		int nTotalGoals = goals_list.size();
		float nTotalProgress = 0;

		for (Goal goal : goals_list) {
			long goalId = goal.getId();

			nTotalProgress = nTotalProgress + getGoalProgress(goalId, date);

		}

		return nTotalProgress / nTotalGoals;
	}*/

	public float getTotalMonthlyProgress(Date date) {
		ArrayList<Goal> goals_list = (ArrayList<Goal>) getGoalsList(Goal.MONTHLY);

		float nTotalGoals = goals_list.size();
		float nTotalProgress = 0;

		for (Goal goal : goals_list) {
			long goalId = goal.getId();

			nTotalProgress = nTotalProgress
					+ getProgressPercent(goalId, new Date());

		}

		return Round(nTotalProgress / nTotalGoals, 1);
	}

	private static class myDbHelper extends SQLiteOpenHelper {

		public myDbHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
		}

		// Called when no database exists in disk and the helper class needs
		// to create a new one.
		@Override
		public void onCreate(SQLiteDatabase _db) {
			_db.execSQL(DATABASE_CREATE_GOAL);
			_db.execSQL(DATABASE_CREATE_GOAL_UPDATE);

		}

		// Called when there is a database version mismatch meaning that the
		// version
		// of the database on disk needs to be upgraded to the current version.
		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
				int _newVersion) {
			// Log the version upgrade.
			/*
			 * Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion +
			 * " to " + _newVersion + ", which will destroy all old data");
			 */
			// Upgrade the existing database to conform to the new version.
			// Multiple
			// previous versions can be handled by comparing _oldVersion and
			// _newVersion
			// values.

			// The simplest case is to drop the old table and create a new one.
			_db.execSQL("DROP TABLE IF EXISTS " + GOAL_TABLE);
			_db.execSQL("DROP TABLE IF EXISTS " + GOAL_UPDATE_TABLE);

			// Create a new one.
			onCreate(_db);
		}
	}

	public int getDaysOfMonth(Date date) {

		Calendar calendar = Calendar.getInstance();

		calendar.setTime(date);

		int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		return days;

	}

	public Date getLastDateOfMonth(Date date) {

		String day = Integer.toString(getDaysOfMonth(date));

		SimpleDateFormat sdf;

		sdf = new SimpleDateFormat("MM");
		String month = sdf.format(date);

		sdf = new SimpleDateFormat("yyyy");
		String year = sdf.format(date);

		String strDate = day + "-" + month + "-" + year;

		DateFormat formatter;
		formatter = new SimpleDateFormat("dd-MM-yyyy");

		Date lastDate = null;
		try {
			lastDate = (Date) formatter.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return lastDate;
	}

	public Date getFirstDateOfMonth(Date date) {

		String day = "01";

		SimpleDateFormat sdf;

		sdf = new SimpleDateFormat("MM");
		String month = sdf.format(date);

		sdf = new SimpleDateFormat("yyyy");
		String year = sdf.format(date);

		String strDate = day + "-" + month + "-" + year;

		DateFormat formatter;
		formatter = new SimpleDateFormat("dd-MM-yyyy");

		Date firstDate = null;
		try {
			firstDate = (Date) formatter.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return firstDate;
	}

	public float Round(float Rval, int Rpl) {
		float p = (float) Math.pow(10, Rpl);
		Rval = Rval * p;
		float tmp = Math.round(Rval);
		return (float) tmp / p;
	}

}
